package com.java.business.jxc.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.java.business.jxc.bean.B_BACK;
import com.java.business.jxc.bean.B_MATERIAL;
import com.java.business.jxc.bean.B_OUTPUT;
import com.java.business.jxc.dao.BackMapper;
import com.java.business.jxc.dao.MaterialMapper;
import com.java.business.jxc.dao.OutputMapper;
import com.java.core.bean.LowerCaseKeyMap;
import com.java.core.utils.IdUtils;

@Transactional
@Service
public class OutputService {

	@Autowired
	private OutputMapper mapper;

	@Autowired
	private MaterialMapper materialMapper;

	@Autowired
	private BackMapper backMapper;

	public void add(B_OUTPUT output) throws RuntimeException {
		output.setOutput_id(IdUtils.uuid());
		B_MATERIAL material = materialMapper.getMaterialById(output.getMaterial_id());
		if (output.getAmount() > material.getResidue()) {
			throw new RuntimeException("当前出库数量 " + output.getAmount() + " 不能大于剩余数量 " + material.getResidue() + "!");
		}
		mapper.add(output);
	}

	public void update(B_OUTPUT output) {
		B_MATERIAL material = materialMapper.getMaterialById(output.getMaterial_id());
		Double amount = mapper.getOutputById(output.getOutput_id()).getAmount();
		Double residue = material.getResidue() + amount;
		if (output.getAmount() > residue) {
			throw new RuntimeException("当前出库数量 " + output.getAmount() + " 不能大于剩余数量 " + material.getResidue() + "!");
		}
		Double outputAmount = mapper.getOutputAmount(output);
		B_BACK back = new B_BACK();
		back.setBuilder_id(output.getBuilder_id());
		back.setMaterial_id(output.getMaterial_id());
		Double backAmount = backMapper.getBackAmount(back);
		if (outputAmount - amount + output.getAmount() < backAmount) {
			throw new RuntimeException("当前出库数量 " + output.getAmount() + " 加上已出库数量 " + (outputAmount - amount)
					+ " 不能小于已退库总量 " + backAmount + "!");
		}
		mapper.update(output);
	}

	public void setDisabled(B_OUTPUT output) {
		mapper.setDisabled(output);
	}

	public void delete(String output_id) {
		B_OUTPUT output = mapper.getOutputById(output_id);
		Double outputAmount = mapper.getOutputAmount(output);
		B_BACK back = new B_BACK();
		back.setBuilder_id(output.getBuilder_id());
		back.setMaterial_id(output.getMaterial_id());
		Double backAmount = backMapper.getBackAmount(back);
		if (outputAmount - output.getAmount() < backAmount) {
			throw new RuntimeException("无法删除该出库信息，删除当前出库数量 " + output.getAmount() + " 会导致总出库量 " + outputAmount
					+ " 小于已退库总量 " + backAmount + "!");
		}
		mapper.delete(output_id);
	}

	public B_OUTPUT getOutputById(String output_id) {
		return mapper.getOutputById(output_id);
	}

	public List<LowerCaseKeyMap> getOutputList(B_OUTPUT output) {
		return mapper.getOutputList(output);
	}
}
